package com.bw.controller;

import com.bw.bean.Dianpu;
import com.bw.bean.Shop;
import com.bw.service.DianpuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class MyController {
    @Resource
    private DianpuService dianpuService;

    @RequestMapping("tolist")
    public String tolist(Dianpu dianpu, Model model,
                      @RequestParam(defaultValue = "1") int pageNum,
                         @RequestParam(defaultValue = "3")    int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Dianpu> list = dianpuService.list(dianpu);
        PageInfo<Dianpu> page = new PageInfo<>(list);
        model.addAttribute("page",page);
        model.addAttribute("dianpu",dianpu);

        return "list";
    }
    @RequestMapping("toadd")
    public String toadd(String did,Model model){
        if(StringUtil.isNotEmpty(did)){
            Dianpu dianpu = dianpuService.getById(did);
            model.addAttribute("dianpu",dianpu);
        }
        return "add";
    }

    @RequestMapping("add")
    public String add(Model model, Dianpu dianpu, MultipartFile file){
        String filename = file.getOriginalFilename();
        String substring = filename.substring(filename.lastIndexOf("."));
        String s = UUID.randomUUID() + substring;

        try {
            file.transferTo(new File("D:\\myupload\\"+s));
            dianpu.setImg("/myupload/"+s);
        } catch (IOException e) {
            e.printStackTrace();
        }


        String did = dianpu.getDid();
        if(StringUtil.isNotEmpty(did)){
            dianpuService.insert(dianpu);
        }

        return "redirect:tolist.do";
    }

    @RequestMapping("getshop")
    @ResponseBody
    public List<Shop> getshop(){
        return dianpuService.getshop();
    }
}
